using System;
using System.Collections.Generic;
using System.Text;
using System.Web;

namespace Melis.Chat
{
	public class HandlerFactory : IHttpHandlerFactory
	{
		#region IHttpHandlerFactory Members

		public IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated)
		{
			return new Base();

		}

		public void ReleaseHandler(IHttpHandler handler)
		{ }

		#endregion

		private class Base : IHttpHandler
		{
			private HttpContext _context;
			public string UserName
			{
				get { return _context.Request["u"]; }
			}

			#region IHttpHandler Members

			public virtual bool IsReusable
			{
				get { return true; }
			}

			public virtual void ProcessRequest(HttpContext context)
			{
				this._context = context;
				context.Response.Expires = 0;
				context.Response.AddHeader("cache-control", "no-cache");

				context.Response.ContentType = "text/plain";
				string operation = context.Request["op"].ToUpper();
				string clientID = context.Request["id"];
				string msg = context.Request["t"];
				string text = Convert.ToString(context.Application["MelisChat" + clientID]);

				context.Response.Write(operation);
				context.Response.Write(clientID + "\n");
				if (operation == "R")//Refresh
				{
					context.Response.Write(text);
				}
				else if (operation == "M")//Refresh
				{
					text += UserName + " says: " + msg + "<br/>\n";
					context.Response.Write(text);
				}
				else if (operation == "J")//Refresh
				{
					text += "<i>"+ UserName + " is Join!</i><br/>\n";
					context.Response.Write(text);
				}

				context.Application["MelisChat" + clientID] = text;
			}

			#endregion
		}
	}
}
